package sealte.mynode.bean;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import sealte.mynode.pojo.Comment;
import sealte.mynode.db.DBConnection;
import sealte.mynode.util.Tools;

/**
 * COMMENT Bean
 * @author SEALTE
 * 2012-11-16
 */
public class CommentBean {
	private Connection conn = null;
	private PreparedStatement ps = null;
	private ResultSet rs = null;
	
	public boolean addNew(Comment com){
		String sql = "INSERT INTO M_COMMENT(F_ESSAY,F_USER,F_CONTENT,F_PARENT,F_WRITETIME,F_MODIFYTIME) "
				   + "VALUES(?,?,?,?,?,?)";
		try{
			conn = DBConnection.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, com.getEssayId());
			ps.setInt(2, com.getUserId());
			ps.setString(3, com.getContent());
			ps.setInt(4, com.getParent());
			ps.setString(5, com.getWriteTime());
			ps.setString(6, com.getModifyTime());
			ps.execute();
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}finally{
			DBConnection.close(null, ps, conn);
		}
	}
	
	public List<Comment> listAllByEssayId(int id){
		String sql = "SELECT C.F_ID,F_USER,U.F_NAME,F_CONTENT,F_PARENT,F_WRITETIME,F_MODIFYTIME "
				   + "FROM M_COMMENT C,M_USER U WHERE C.F_USER=U.F_ID AND F_ESSAY=? ORDER BY F_PARENT,C.F_ID";
		List<Comment> all = new ArrayList<Comment>();
		try{
			conn = DBConnection.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, id);
			rs = ps.executeQuery();
			while(rs.next()){
				Comment com = new Comment();
				com.setId(rs.getInt("F_ID"));
				com.setUserId(rs.getInt("F_USER"));
				com.setUser(rs.getString("F_NAME"));
				com.setContent(rs.getString("F_CONTENT").replaceAll("\n\r", "<br/>"));
				com.setParent(rs.getInt("F_PARENT"));
				com.setWriteTime(Tools.getDateTimeRF(rs.getString("F_WRITETIME")));
				com.setModifyTime(Tools.getDateTimeRF(rs.getString("F_MODIFYTIME")));
				com.setEssayId(id);
				all.add(com);
			}
			return all;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}finally{
			DBConnection.close(rs, ps, conn);
		}
	}
	
	
}
